package toOffer;

/**
 * @author YuanAo
 * @date 2024/7/3 10:05
 * @description 两两交换链表中的节点
 */

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。
 *
 * 例子：
 * 输入：head = [1,2,3,4]
 * 输出：[2,1,4,3]
 */
public class No24 {
    public static void main(String[] args) {
        int[] ints = {1, 2, 3, 4, 5};
        ListNode head = null;
        for (int i = ints.length - 1; i >= 0; i--) {
            if (i != ints.length - 1) {
                head = new ListNode(ints[i], head);
            } else {
                head = new ListNode(ints[i]);
            }
        }

//        ListNode listNode = head;
        ListNode listNode = swapPairs(head);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }
    }

    /**
     *
     * @param head
     * @return
     */
    public static ListNode swapPairs(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return head;

        List<Integer> tempList = new ArrayList<>();
        List<Integer> list = linkedNodeToArrayList(head);
        if (list.size() % 2 != 0){
            for (int i = 0; i < list.size() - 1; i = i + 2) {
                tempList.add(list.get(i + 1));
                tempList.add(list.get(i));
            }
            tempList.add(list.get(list.size() - 1));
        }else {
            for (int i = 0; i < list.size(); i = i + 2) {
                tempList.add(list.get(i + 1));
                tempList.add(list.get(i));
            }
        }

        return arrayListToLinkedNode(tempList);
    }

    public static List<Integer> linkedNodeToArrayList(ListNode node) {
        ArrayList<Integer> list = new ArrayList<>();
        while (node != null) {
            list.add(node.val);
            node = node.next;
        }
        return list;
    }

    public static ListNode arrayListToLinkedNode(List<Integer> list) {
        ListNode head = null;
        for (int i = list.size() - 1; i >= 0; i--) {
            if (i == list.size() - 1) {
                head = new ListNode(list.get(i));
            } else {
                head = new ListNode(list.get(i), head);
            }
        }
        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
